<!-- 云模型创建类型 -->
<template>
  <el-dialog
    class="dialogAdapter"
    destroy-on-close
    @close="handleCancel"
    style="border-radius: 10px"
    v-model="props.visible"
    :title="`${type === 'add' ? '创建' : '编辑'}`"
  >
    <!--云模型from -->
    <el-form ref="ruleFormRef" :model="modelForm" label-position="top">
      <!-- @vue-ignore -->
      <el-upload
        class="avatar-uploader"
        action="#"
        :before-upload="beforeAvatarUpload"
        :http-request="handleRequestUpload"
        accept="image/jpg, image/jpeg, image/png"
        :show-file-list="false"
      >
        <img v-if="modelForm.avatar && isShowAvatar" :src="modelForm.avatar" class="cover-img" />
        <img v-if="modelForm.avatar && isShowAvatar" :src="EditAvatarSvg" alt="" class="edit-svg" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>

      <el-form-item prop="nickname" label="姓名" :rules="[{ required: true, message: '请输入姓名' }]">
        <el-input v-model="modelForm.nickname" autocomplete="off" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item
        prop="label_id"
        label="标签"
        :rules="[{ required: true, message: '请选择标签', trigger: 'change' }]"
      >
        <el-select v-model="modelForm.label_id" placeholder="请选择标签" :style="{ width: '100%' }">
          <el-option
            v-for="item in robotLabelList"
            :class="[{ option: item.type === '1' }]"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        prop="category"
        label="模板"
        :rules="[{ required: true, message: '请选择模板', trigger: 'change' }]"
      >
        <!-- :disabled="type !== 'add'" -->
        <el-select v-model="modelForm.category" placeholder="请选择模板" :style="{ width: '100%' }">
          <el-option v-for="item in templateList" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item
        prop="info"
        label="备注"
        :rules="[{ required: true, message: '请填写智能体备注', trigger: 'change' }]"
      >
        <el-input v-model="modelForm.info" type="textarea" placeholder="请填写智能体备注" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="danger"
          :loading="btnLoading"
          :disabled="shouldDisableButton"
          @click="handleSubmitForm(ruleFormRef)"
        >
          {{ type === "add" ? "创建" : "编辑" }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { AddRobot, EditRobot, getRobotLabelList } from "@/api/cloud"
import { RobotLabelListProps } from "@/api/cloud/types/cloud"
import EditAvatarSvg from "@/assets/drawing/edit.svg"
import debounce from "@/utils/debounce"
import { ElMessage, UploadProps, type FormInstance } from "element-plus"
import { computed, onMounted, ref } from "vue"

export type CategoryType = "BASE" | "NPC" | "LAW" | "JSON"

export interface ModelFormProps {
  avatar: any
  nickname: string
  info?: string
  category: CategoryType
  label_id?: number
  id?: number
  isShowAvatar?: boolean
}

interface Props {
  editData?: ModelFormProps
  type?: "add" | "edit"
  visible: boolean
}

interface CategoryListProps {
  id: number
  label: string
  value: string
}

const props = defineProps<Props>()
const emits = defineEmits(["editDpData", "close", "update-init"])
const ruleFormRef = ref<any>(null)
const btnLoading = ref<boolean>(false)
const isShowAvatar = ref<boolean>(Boolean(props.editData && props.editData.isShowAvatar) as any)
const modelForm = ref<ModelFormProps>(props.editData as ModelFormProps)
const avatarImgFile = ref<any>(null)
const templateList = ref<CategoryListProps[]>([
  { id: 1, label: "BASE", value: "BASE" },
  { id: 2, label: "NPC", value: "NPC" },
  { id: 3, label: "LAW", value: "LAW" },
  { id: 4, label: "JSON", value: "JSON" },
  // 3.30新增CPN-虚拟伴侣/SHG-导购/STAFF-AI员工
  { id: 5, label: "CPN", value: "CPN" },
  { id: 6, label: "SHG", value: "SHG" },
  { id: 7, label: "STAFF", value: "STAFF" }
])
const robotLabelList = ref<RobotLabelListProps[]>([])

// 初始化标签模型
const initLabelModel = async () => {
  const { data } = await getRobotLabelList({ page: 1 })

  const list = [] as any
  data.list.forEach((item: any) => {
    list.push(item)
    if (item.label_list) {
      item.label_list.forEach((value: any) => {
        list.push({
          ...value,
          type: "1"
        })
      })
    }
  })
  console.log(list)

  robotLabelList.value = list
}

onMounted(initLabelModel)

const shouldDisableButton = computed(() => {
  const { avatar, nickname, info, category, label_id } = modelForm.value

  const isNonEmptyString = (value: any) => {
    return typeof value === "string" && value.trim() !== ""
  }

  const isNonEmptyArray = (value: any) => {
    return Array.isArray(value) && value.length > 0
  }

  return (
    ![avatar, nickname, info, category, label_id].every((value) => {
      return isNonEmptyString(value) || isNonEmptyArray(value) || typeof value === "number"
    }) || !isShowAvatar.value
  )
})

// 上传头像之前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const image = new Image()
  const reader = new FileReader()

  return new Promise((resolve, reject) => {
    reader.onload = (e) => {
      if (typeof reader.result === "string") {
        image.src = reader.result
        image.onload = () => {
          const width = image.width
          const height = image.height
          if (width !== height) {
            ElMessage.error("头像图片必须为(1:1比例)")
            reject()
          } else {
            resolve()
          }
        }
      } else {
        reject()
      }
    }

    reader.readAsDataURL(rawFile)
  })
}

// 上传头像
const handleRequestUpload = debounce((file: any) => {
  if (file) {
    const allowedFormats = ["image/jpeg", "image/jpg", "image/png"]
    if (!allowedFormats.includes(file.file?.type)) {
      ElMessage({
        type: "error",
        message: "格式错误，只能上传 jpeg / jpg / png 图片格式"
      })
      return
    }

    const URL = window.URL || window.webkitURL
    avatarImgFile.value = file.file
    const imgSrc = URL.createObjectURL(file.file)
    isShowAvatar.value = true
    modelForm.value.avatar = imgSrc
  }
}, 300)

// 提交表单按钮
const handleSubmitForm = debounce((formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        btnLoading.value = true
        // if (avatarImgFile.value instanceof File) {
        //   modelForm.value.avatar = avatarImgFile.value
        // } else {
        //   modelForm.value.avatar = JSON.stringify({})
        // }

        // 提交表单数据时，移除自定义参数
        delete modelForm.value.isShowAvatar

        if (props.type === "add") {
          await AddRobot({ ...modelForm.value, avatar: avatarImgFile.value })
        } else {
          let avatar: any = null
          if (avatarImgFile.value instanceof File) {
            avatar = avatarImgFile.value
          } else {
            avatar = JSON.stringify({})
          }
          // @ts-ignore
          await EditRobot({ ...modelForm.value, avatar, id: modelForm.value.id })
        }
        ElMessage({
          type: "success",
          message: `${props.type === "add" ? "新增" : "编辑"}成功`
        })
        handleClose("cloud")
      } catch (error: any) {
        ElMessage({
          type: "error",
          message: error.message || "异常错误"
        })
      } finally {
        btnLoading.value = false
      }
    } else {
      console.log("error submit!")
      return false
    }
  })
}, 300)

const handleClose = (type: string) => {
  emits("close", type)
  if (type) {
    handleCancel()
  }
}

const handleCancel = () => {
  if (ruleFormRef.value) {
    modelForm.value = {
      avatar: "",
      nickname: "",
      category: "BASE",
      label_id: undefined,
      info: "",
      id: undefined
    }
    avatarImgFile.value = null
    isShowAvatar.value = false
    ruleFormRef.value.resetFields() // 重置表单
  }
  handleClose("")
}
</script>

<style lang="scss" scoped>
.option {
  font-size: 12px;
  padding-left: 30px;
  color: #999;
}
.avatar-uploader {
  position: relative;
  text-align: center;
  margin-bottom: 20px;

  .cover-img {
    width: 80px;
    height: 80px;
    border-radius: 20px;
  }

  .edit-svg {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 32px;
    height: 32px;
    border-radius: 20px 0px;
    opacity: 0.8;
  }
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 20px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  text-align: center;
}
</style>
